package com.lemon.boot.common.utils;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @author 李猛
 * @datetime 2024/5/29 10:07
 * @description 类对象
 */
@Slf4j
public final class SocketUtil {

    /**
     * 从 session里获取用户ID
     *
     * @param session
     * @return
     */
    public static Long getUserId(Session session) {
        Object value = getByKey(session, "id");
        return NumberUtil.parseLong(Objects.toString(value));
    }

    /**
     * 根据key从 session里获取信息
     *
     * @param session
     * @return
     */
    public static Object getByKey(Session session, String key) {
        Map<String, Object> userProperties = session.getUserProperties();
        return userProperties.get(key);
    }

    /**
     * 发送字符串
     *
     * @param session
     * @param message
     */
    public static void sendStr(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("WebSocketUtil.baseSendStr.message:{}", e.getMessage());
            try {
                session.getBasicRemote().sendText("失败！");
            } catch (IOException ex) {
                log.error("WebSocketUtil.baseSendStr.message:{}", ex.getMessage());
            }
        }
    }

    /**
     * 发送 JSON字符串
     *
     * @param session
     * @param message
     */
    public static void sendJson(Session session, Object message) {
        try {
            session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
        } catch (IOException e) {
            log.error("WebSocketUtil.baseSendJson.message:{}", e.getMessage());
            try {
                session.getBasicRemote().sendText("失败！");
            } catch (IOException ex) {
                log.error("WebSocketUtil.baseSendJson.message:{}", ex.getMessage());
            }
        }
    }

    /**
     * 关闭
     *
     * @param session
     */
    public static void close(Session session) {
        try {
            session.close();
        } catch (IOException e) {
            log.error("WebSocketUtil.baseSendJson.message:{}", e.getMessage());
        }
    }
}
